/*
 * @Author: Orangepi - xcy2001@sina.cn
 * @Date: 2022-01-01 01:46:54
 * @LastEditTime: 2022-01-01 02:45:34
 * @LastEditors: Orangepi - xcy2001@sina.cn
 * @Description: 处理登录相关事务
 * @FilePath: \college-application-enrollment-backend\src\services\LoginService.js
 */

const crypto = require('crypto');
const userLogin = require("../models/user_login")
class LoginService {

    generateUUID() {
        var d = new Date().getTime();
        var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            var r = (d + Math.random() * 16) % 16 | 0;
            d = Math.floor(d / 16);
            return (c == 'x' ? r : (r & 0x7 | 0x8)).toString(16);
        });
        return uuid;
    }
    /**
     * 
     * @param {string} uname 用户名
     * @param {string} upsd 用户密码
     * @returns 
     */
    async Register(uname, upsd) {
        let res=await userLogin.QueryUser(uname).catch(err=>{return{unsuccess:true,err}});
        if(res.unsuccess){
            console.log("err:",res.err);
            throw new Error("查询用户异常:"+res.err)
        }
        if(res.length>0){
            throw new Error("用户名已存在")
        }
        const UUID=this.generateUUID();
        const hashPsd=crypto.createHash("sha256").update(upsd).update(UUID).digest("hex");
        res=await userLogin.InsertUser(uname,hashPsd,UUID).catch(err=>{return{unsuccess:true,err}});
        if(res.unsuccess){
            console.log("err:",res.err);
            throw new Error("新建用户异常:")
        }
        if(res.affectedRows===1){
          return res.affectedRows;
        }else{
            console.log("err:",res);
          throw new Error("新建用户异常:")
        }
    }
}
module.exports = new LoginService();